"""主应用程序入口"""

import sys
import tkinter as tk
from tkinter import messagebox
import asyncio
import threading
from pathlib import Path

from .gui.main_window import MainWindow
from .utils.config_manager import ConfigManager
from .utils.database import Database
from .utils.logger import setup_logging, get_logger


class FileOrganizerApp:
    """文件归纳所主应用程序"""
    
    def __init__(self):
        """初始化应用程序"""
        # 设置日志
        self.logger = setup_logging()
        self.logger.info("文件归纳所启动中...")
        
        # 初始化配置
        self.config_manager = ConfigManager()
        self.config = self.config_manager.load_config()
        
        # 初始化数据库
        db_path = self.config.app.database_path.expanduser()
        self.database = Database(db_path)
        
        # 创建主窗口
        self.root = tk.Tk()
        self.main_window = None
        
        # 设置应用程序属性
        self._setup_app()
        
        # 异步事件循环
        self.loop = None
        self._setup_async_loop()
    
    def _setup_app(self) -> None:
        """设置应用程序属性"""
        self.root.title(self.config.app.app_name)
        self.root.geometry(f"{self.config.app.window_size[0]}x{self.config.app.window_size[1]}")
        self.root.minsize(*self.config.app.min_window_size)
        
        # 设置应用图标（如果有的话）
        try:
            icon_path = Path(__file__).parent / "resources" / "icons" / "app.ico"
            if icon_path.exists():
                self.root.iconbitmap(str(icon_path))
        except Exception:
            pass
        
        # 设置关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self._on_closing)
    
    def _setup_async_loop(self) -> None:
        """设置异步事件循环"""
        def run_async_loop():
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)
            self.loop.run_forever()
        
        self.async_thread = threading.Thread(target=run_async_loop, daemon=True)
        self.async_thread.start()
    
    def run(self) -> None:
        """运行应用程序"""
        try:
            # 初始化主窗口
            self.main_window = MainWindow(
                root=self.root,
                config=self.config,
                database=self.database,
                async_loop=self.loop
            )
            
            self.logger.info("应用程序启动完成")
            
            # 启动GUI主循环
            self.root.mainloop()
            
        except Exception as e:
            self.logger.critical(f"应用程序启动失败: {e}")
            messagebox.showerror("启动错误", f"应用程序启动失败：\n{e}")
            sys.exit(1)
    
    def _on_closing(self) -> None:
        """应用程序关闭事件"""
        try:
            self.logger.info("正在关闭应用程序...")
            
            # 保存配置
            self.config_manager.save_config()
            
            # 清理数据库连接
            if hasattr(self.database, 'cleanup_expired_cache'):
                self.database.cleanup_expired_cache()
            
            # 停止异步循环
            if self.loop and self.loop.is_running():
                self.loop.call_soon_threadsafe(self.loop.stop)
            
            # 销毁主窗口
            self.root.quit()
            self.root.destroy()
            
            self.logger.info("应用程序已关闭")
            
        except Exception as e:
            self.logger.error(f"关闭应用程序时出错: {e}")
        finally:
            sys.exit(0)


def main():
    """主函数"""
    try:
        app = FileOrganizerApp()
        app.run()
    except KeyboardInterrupt:
        print("\n应用程序被用户中断")
        sys.exit(0)
    except Exception as e:
        print(f"应用程序出现未处理的错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()